﻿using System;
using System.Collections.Specialized;
using System.Text;
using System.Text.RegularExpressions;
using App_Code.Helpers;
using Rss;

namespace App_Code.SiteParsers
{
    /// <summary>
    /// Summary description for SdarotNet
    /// </summary>
    public class SdarotNet : BasePluginParser
    {
        private const string DEFAULT_URL = "http://sdarot.net/category/tube";
        protected const string SEARCH_URL = "http://sdarot.net/?s={0}&x=0&y=0";

        public SdarotNet()
        {
            this._defaultUrl = DEFAULT_URL;

            this.Name = "Sdarot.Net";
            this.Description = "אתר צפייה ישירה";
            this.Url = DEFAULT_URL;
        }

        #region Implementation of IPluginParser
        public override RssFeed Run(NameValueCollection queryStringParams)
        {
            this.InitMembers(queryStringParams);

            switch (this._pluginMode)
            {
                case PluginMode.IDLE_MODE:
                    return this.LoadCategories();

                case PluginMode.CATEGORIES_MODE:
                    return this.LoadABCSeries();

                case PluginMode.MOVIES_MODE:
                    return this.LoadMovies();

                case PluginMode.NEXT_PAGE_MODE:
                    return this.LoadMovies();

                case PluginMode.MOVIE_MODE:
                    return this.LoadMovie();

                case PluginMode.SEARCH_MODE:
                    this.Url = string.Format(SEARCH_URL, this.SearchText);
                    return this.LoadMovies();

                default:
                    throw new Exception("Unknown mode");
            }
        }

        public override void RunUntillPage(int pageNumber)
        {
            for (var i = 1; i <= pageNumber; i++)
            {
                this.Url = string.Format("{0}page/{1}", DEFAULT_URL, i);
                this.LoadMovies();
            }
        }

        #endregion

        #region Private Methods
        private RssFeed LoadCategories()
        {
            try
            {
                var feed = LoadFromCache(this.Url);
                if (feed != null) return feed;

                var page = Utils.GetPage(this.Url, Encoding.UTF8);

                var rssChannel = new RssChannel
                {
                    Title = string.Format("Movies Channel - {0}", DateTime.Now),
                    Description = "Categories List",
                    Link = new Uri(string.Format("{0}?pluginId={1}", Utils.GetSiteUrl(), this._pluginId)),
                    Language = "he"
                };

                rssChannel.LastBuildDate = rssChannel.Items.LatestPubDate();

                this.AddSearchLink(rssChannel, SEARCH_URL);

                this.AddABCLink(rssChannel, DEFAULT_URL);

                const string categoriesSectionRegEx = "<a href=\"http://sdarot.net/category/tube\">סדרות לצפייה ישירה</a>(.+?)</ul>";
                var categoriesSection = Regex.Match(page, categoriesSectionRegEx, RegexOptions.Singleline).Groups[1].Value;

                const string categoriesLinkRegEx = "<a href=\"(.+?)\">(.+?)</a>";
                var matches = Regex.Matches(categoriesSection, categoriesLinkRegEx, RegexOptions.Singleline);
                foreach (Match match in matches)
                {
                    var categoryPageLink = match.Groups[1].Value;
                    var categoryTitle = match.Groups[2].Value;

                    var movie = new Movie
                    {
                        Name = categoryTitle,
                    };

                    movie.MovieLinks.Add(categoryPageLink);

                    var movieItems = movie.GetRssItems(Utils.GetSiteUrl(), this._pluginId, (int)PluginMode.MOVIES_MODE);
                    foreach (var movieItem in movieItems)
                    {
                        rssChannel.Items.Add(movieItem);
                    }
                }

                feed = new RssFeed { Encoding = Encoding.UTF8 };
                feed.Channels.Add(rssChannel);

                this.AddToCache(this.Url, feed);

                return feed;
            }
            catch (Exception ex)
            {
                return CreateErrorResponse(ex.Message);
            }
        }

        private RssFeed LoadABCSeries()
        {
            try
            {
                var feed = LoadFromCache(this.Url);
                if (feed != null) return feed;

                var page = Utils.GetPage(this.Url, Encoding.UTF8);

                var rssChannel = new RssChannel
                {
                    Title = "Movies Channel",
                    Description = "Movies List",
                    Link = new Uri(string.Format("{0}?pluginId={1}", Utils.GetSiteUrl(), this._pluginId)),
                    Language = "he"
                };

                rssChannel.LastBuildDate = rssChannel.Items.LatestPubDate();

                const string abcSectionRegEx = "<h3 class=\"widget-title\"> כל הסדרות באתר א-ת</h3>.*?</div>";
                var categoriesSection = Regex.Match(page, abcSectionRegEx, RegexOptions.Singleline).Groups[0].Value;

                const string itemsSectionRegEx = "<a href=\"(.+?)\">(.+?)</a>";
                var matches = Regex.Matches(categoriesSection, itemsSectionRegEx, RegexOptions.Singleline);

                foreach (Match match in matches)
                {
                    var seriesPageLink = match.Groups[1].Value;
                    var seriesTitle = match.Groups[2].Value;

                    var movie = new Movie
                    {
                        Name = seriesTitle,
                    };

                    movie.MovieLinks.Add(seriesPageLink);

                    var movieItems = movie.GetRssItems(Utils.GetSiteUrl(), this._pluginId, (int)PluginMode.MOVIES_MODE);
                    foreach (var movieItem in movieItems)
                    {
                        rssChannel.Items.Add(movieItem);
                    }
                }

                feed = new RssFeed { Encoding = Encoding.UTF8 };
                feed.Channels.Add(rssChannel);

                AddToCache(this.Url, feed);

                return feed;
            }
            catch (Exception ex)
            {
                return CreateErrorResponse(ex.Message);
            }
        }

        private RssFeed LoadMovies()
        {
            try
            {
                var feed = LoadFromCache(this.Url);
                if (feed != null) return feed;

                var page = Utils.GetPage(this.Url, Encoding.UTF8);

                var rssChannel = new RssChannel
                                     {
                                         Title = "Movies Channel",
                                         Description = "Movies List",
                                         Link = new Uri(string.Format("{0}?pluginId={1}", Utils.GetSiteUrl(), this._pluginId)),
                                         Language = "he"
                                     };

                rssChannel.LastBuildDate = rssChannel.Items.LatestPubDate();

                var sessonMatches = page.Split(new[] { "<h5 class=\"toggle\">" }, StringSplitOptions.RemoveEmptyEntries);

                

                foreach (var match in sessonMatches)
                {
                    //const string sessionSectionRegEx = "<h5 class=\"toggle\"><a href.*?>(.+?)</a></h5>(.+?)";
                    //var sessonMatches = Regex.Matches(page, sessionSectionRegEx, RegexOptions.Singleline);

                    //var moviePageLink = match.Groups[1].Value;
                    //var movieTitle = match.Groups[2].Value;
                    //var imageLink = match.Groups[3].Value;
                    //var plot = match.Groups[4].Value;

                    //var movie = new Movie
                    //                {
                    //                    Name = movieTitle,
                    //                    ImageLink = imageLink,
                    //                    Plot = plot
                    //                };

                    //var pageContent = Utils.GetPage(moviePageLink, Encoding.UTF8);
                    //movie.MovieLinks = GetMovieLinks(pageContent);

                    //var movieItems = movie.GetRssItems(Utils.GetSiteUrl(), this._pluginId, (int)PluginMode.MOVIE_MODE);
                    //foreach (var movieItem in movieItems)
                    //{
                    //    //var rssCategory = new RssCategory { Name = "MegaVideo" };
                    //    //movieItem.Categories.Add(rssCategory);
                    //    rssChannel.Items.Add(movieItem);
                    //}
                }

                var nextPageMovie = new Movie
                                        {
                                            Name = "דף הבא",
                                        };

                nextPageMovie.MovieLinks.Add(GetNextPageLink(page));
                var nextPageItems = nextPageMovie.GetRssItems(Utils.GetSiteUrl(), this._pluginId, (int)PluginMode.NEXT_PAGE_MODE);
                rssChannel.Items.Add(nextPageItems[0]);

                feed = new RssFeed { Encoding = Encoding.UTF8 };
                feed.Channels.Add(rssChannel);

                AddToCache(this.Url, feed);

                return feed;
            }
            catch (Exception ex)
            {
                return CreateErrorResponse(ex.Message);
            }
        }

        private string GetNextPageLink(string pageContent)
        {
            try
            {
                const string nextPageExpression = "class=\"numeric_onclick\">.*?<a href=\"(.+?)\"";
                var exp = new Regex(nextPageExpression, RegexOptions.Singleline);
                var match = exp.Match(pageContent);
                if (match.Success)
                {
                    return match.Groups[1].Value.Trim();
                }
            }
            catch { }

            return this.Url;
        }

        protected void AddABCLink(RssChannel rssChannel, string searchUrl)
        {
            var movie = new Movie
            {
                Name = "כל הסדרות מ א-ת",
            };

            movie.MovieLinks.Add(searchUrl);

            var movieItems = movie.GetRssItems(Utils.GetSiteUrl(), this._pluginId, (int)PluginMode.CATEGORIES_MODE);
            foreach (var movieItem in movieItems)
            {
                rssChannel.Items.Add(movieItem);
            }
        }
        #endregion
    }
}